<template>
  <div class="app-container">
    <el-form :inline="true" class="mb20">
      <el-form-item label="充电站名称">
        <el-select v-model="selectedStationId" placeholder="请选择充电站" @change="onStationChange" style="width: 200px">
          <el-option v-for="item in stationList" :key="item.csId" :label="item.csName" :value="item.csId" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-date-picker v-model="selectedMonth" type="month" placeholder="选择月份" style="width: 150px" @change="onMonthChange"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="refreshAll">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <div class="card card-purple">
          <div>充电枪使用数</div>
          <div class="card-value">{{ overview.gunUseCount || 0 }}把</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card card-blue">
          <div>充电枪使用率</div>
          <div class="card-value">{{ (overview.gunUseRate || 0).toFixed(2) }}%</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card card-cyan">
          <div>正常工作时长</div>
          <div class="card-value">{{ overview.totalWorkHour || 0 }}小时</div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <v-chart :option="lineOption" style="height:300px;" />
      </el-col>
      <el-col :span="12">
        <v-chart :option="barOption" style="height:300px;" />
      </el-col>
    </el-row>

    <el-table :data="dailyList" border>
      <el-table-column prop="day" label="日期" />
      <el-table-column prop="gunUseCount" label="充电枪使用数（把）" />
      <el-table-column prop="gunUseRate" label="充电枪使用率（%）" :formatter="rateFormat" />
      <el-table-column prop="totalWorkHour" label="充电枪正常工作时长（小时）" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getStationList, getGunAnalysis, getGunAnalysisDaily } from '@/api/system/cgrecord'
import { use } from "echarts/core"
import VChart from "vue-echarts"
import { CanvasRenderer } from "echarts/renderers"
import { LineChart, BarChart } from "echarts/charts"
import { GridComponent, TooltipComponent, LegendComponent } from "echarts/components"

use([CanvasRenderer, LineChart, BarChart, GridComponent, TooltipComponent, LegendComponent])

const stationList = ref([])
const selectedStationId = ref(null)
const selectedMonth = ref(null)
const overview = ref({})
const dailyList = ref([])

const lineOption = ref({})
const barOption = ref({})

onMounted(() => {
  fetchStationList()
})

function fetchStationList() {
  getStationList().then(res => {
    stationList.value = res.data || []
    if (stationList.value.length > 0) {
      selectedStationId.value = stationList.value[0].csId
      refreshAll()
    }
  })
}

function refreshAll() {
  if (!selectedStationId.value || !selectedMonth.value) return
  const monthStr = getMonthStr()
  if (!monthStr) {
    alert('请选择月份')
    return
  }
  console.log('stationId:', selectedStationId.value, 'month:', monthStr, 'rawMonth:', selectedMonth.value)
  fetchOverview()
  fetchDaily()
}

function onStationChange() {
  refreshAll()
}

function onMonthChange() {
  fetchDaily()
}

function fetchOverview() {
  const monthStr = getMonthStr()
  getGunAnalysis(selectedStationId.value, monthStr).then(res => {
    overview.value = res.data || {}
  })
}

function fetchDaily() {
  const monthStr = getMonthStr()
  console.log('fetchDaily monthStr:', monthStr)
  getGunAnalysisDaily(selectedStationId.value, monthStr).then(res => {
    let list = res.data || []
    dailyList.value = list
    updateCharts()
  })
}

function updateCharts() {
  // 折线图
  lineOption.value = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['使用数量', '使用率'] },
    xAxis: { type: 'category', data: dailyList.value.map(i => i.day) },
    yAxis: [{ type: 'value', name: '使用数量' }, { type: 'value', name: '使用率(%)' }],
    series: [
      {
        name: '使用数量',
        type: 'line',
        data: dailyList.value.map(i => i.gunUseCount)
      },
      {
        name: '使用率',
        type: 'line',
        yAxisIndex: 1,
        data: dailyList.value.map(i => Number(i.gunUseRate).toFixed(2))
      }
    ]
  }
  // 柱状图
  barOption.value = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['正常工作时长'] },
    xAxis: { type: 'category', data: dailyList.value.map(i => i.day) },
    yAxis: { type: 'value', name: '正常工作时长(小时)' },
    series: [
      {
        name: '正常工作时长',
        type: 'bar',
        data: dailyList.value.map(i => i.totalWorkHour)
      }
    ]
  }
}

function rateFormat(row) {
  return Number(row.gunUseRate).toFixed(2)
}

function getMonthStr() {
  if (!selectedMonth.value) return '' // 没选月份就返回空字符串
  // 如果是字符串（如 "2025-06" 或 "2025-06-01"）
  if (typeof selectedMonth.value === 'string') {
    // 只取前7位
    return selectedMonth.value.slice(0, 7)
  }
  // 如果是 Date 对象
  if (selectedMonth.value instanceof Date) {
    const y = selectedMonth.value.getFullYear()
    const m = selectedMonth.value.getMonth() + 1
    return `${y}-${m < 10 ? '0' + m : m}`
  }
  // 如果是 dayjs/moment 对象
  if (selectedMonth.value.format) return selectedMonth.value.format('YYYY-MM')
  return ''
}
</script>

<style scoped>
.card {
  background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);
  color: #333;
  padding: 20px 10px;
  border-radius: 10px;
  margin-bottom: 10px;
  text-align: center;
}
.card-value {
  font-size: 2em;
  font-weight: bold;
  margin-top: 10px;
}
.card-blue { background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);}
.card-cyan { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);}
.card-purple { background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);}
.mb20 { margin-bottom: 20px; }
</style>
